package com.lottery.material.controller.portal.portaluser;

import com.lottery.material.aspect.CheckLogIn;
import com.lottery.material.common.JsonResult;
import com.lottery.material.controller.base.BaseController;
import com.lottery.material.dto.portal.PortalUserInfoDto;
import com.lottery.material.entity.portaluser.FollowInfo;
import com.lottery.material.entity.portaluser.PortalUserInfo;
import com.lottery.material.entity.portaluser.ValidateCodeRecord;
import com.lottery.material.exception.ResponseException;
import com.lottery.material.service.portal.portaluser.FollowInfoService;
import com.lottery.material.service.portal.portaluser.PortalUserInfoService;
import com.lottery.material.service.portal.portaluser.ValidateCodeRecordService;
import com.lottery.material.utils.EmptyUtil;
import com.lottery.material.utils.MD5Util;
import com.lottery.material.utils.RedisUtil;
import com.lottery.material.vo.BaseBody;
import com.lottery.material.vo.portaluser.SignInVo;
import com.lottery.material.vo.portaluser.PortalUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@Api(value = "前端用户接口", tags = { "前端用户接口" })
@RestController
@RequestMapping("/material/open/api")
@Slf4j
public class PortalUserInfoController extends BaseController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    PortalUserInfoService portalUserInfoService;

    @Autowired
    ValidateCodeRecordService validateCodeRecordService;

    @Autowired
    FollowInfoService followInfoService;

    @PostMapping("/portalUser/getVerificationCode")
    public JsonResult getVerificationCode(@RequestParam String phoneNumber){
        return JsonResult.success("验证码已发送");
    }

    @ApiOperation(value="验证码校验接口", notes="验证码校验接口（注册、登录、银行预留手机号、找回密码）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "validateCode", value = "验证码", required = true, dataType = "String")
    })
    @PostMapping("/portalUser/verifyCode")
    public JsonResult verifyCode(@NotEmpty String phoneNumber,@NotEmpty String validateCode){
        Map<String,String> map = new HashMap();
        ValidateCodeRecord byPhoneNumber = validateCodeRecordService.findFirstByPhoneNumberOrderByCreateTimeDesc(phoneNumber);
        if(EmptyUtil.isNotEmpty(byPhoneNumber)){
            if(validateCode.equals(byPhoneNumber.getValidateCode())){
                map.put("phoneNumber",phoneNumber);
                return JsonResult.success("验证成功",map);
            }else {
                return JsonResult.failure("验证码错误！");

            }
        }else {
            return JsonResult.failure("验证失败");
        }
    }

    @ApiOperation(value="注册接口", notes="用户使用手机号密码注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
    })
    @PostMapping("/portalUser/signUp")
    public JsonResult signUp(@Valid PortalUserVo signUpVo){
        Optional<PortalUserInfo> portalUser = portalUserInfoService.findByLoginPhoneNumberAndUserStatusNot(signUpVo.getPhoneNumber(),3);
        if(portalUser.isPresent()){
            return JsonResult.failure("手机号已注册，请使用密码登录");
        }
        Map<String,String> map = new HashMap();
        PortalUserInfo portalUserInfo = new PortalUserInfo();
        portalUserInfo.setLoginPhoneNumber(signUpVo.getPhoneNumber());
//        String salt = StringUtil.getRandomNumChar(8);
        portalUserInfo.setLoginPassword(MD5Util.MD5(signUpVo.getPassword()));
//        portalUserInfo.setSalt(salt);
        String userId = UUID.randomUUID().toString();
        portalUserInfo.setUserId(userId);
        String accessToken = UUID.randomUUID().toString();
        portalUserInfo.setAccessToken(accessToken);
        portalUserInfo.setUserStatus(1);
        map.put("userId",userId);
        map.put("accessToken",accessToken);
        portalUserInfoService.save(portalUserInfo);
        return JsonResult.success("注册成功，请使用账号密码登录",map);
    }

    @ApiOperation(value="前端用户登录接口", notes="用户使用手机号密码或者手机验证码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginPhoneNumber", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "loginType", value = "登录类型", required = true, dataType = "String"),
            @ApiImplicitParam(name = "passwordOrCode", value = "密码或验证码", required = true, dataType = "String")
    })
    @PostMapping("/portalUser/signIn")
    public JsonResult signIn(@Valid SignInVo signInVo) {
        Map<String,String> map = new HashMap();
        Optional<PortalUserInfo> portalUser = portalUserInfoService.findByLoginPhoneNumberAndUserStatusNot(signInVo.getLoginPhoneNumber(),3);
        if(portalUser==null){
            throw new ResponseException(403,"用户不存在");
        }
        if(portalUser.get().getUserStatus()==2){
            throw new ResponseException(403,"用户被禁用");
        }
        //密码登录
        if("1".equals(signInVo.getLoginType())){
            if(!portalUser.get().getLoginPassword().equals(MD5Util.MD5(signInVo.getPasswordOrCode()))){
                throw new ResponseException(403,"密码不正确");
            }
            signin(map, portalUser.get());
        }
        //短信验证码登录
        if("2".equals(signInVo.getLoginType())){
            ValidateCodeRecord validateCodeRecord = validateCodeRecordService.findFirstByPhoneNumberOrderByCreateTimeDesc(signInVo.getLoginPhoneNumber());
            if(!signInVo.getPasswordOrCode().equals(validateCodeRecord)){
                throw new ResponseException(403,"验证码错误！");
            }
            signin(map, portalUser.get());
        }
        return JsonResult.success("登录成功",map);
    }

    private void signin(Map<String, String> map, PortalUserInfo portalUser) {
        map.put("userId",portalUser.getUserId());
        String accessToken = UUID.randomUUID().toString();
        map.put("accessToken",accessToken);
        redisUtil.hset("portalUser",portalUser.getUserId(),accessToken);
        portalUser.setAccessToken(accessToken);
        portalUserInfoService.update(portalUser);
    }


    @ApiOperation(value="重置密码接口", notes="重置密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
    })
    @PostMapping("/portalUser/updatePwd")
    public JsonResult updatePwd(@Valid PortalUserVo portalUserVo) {
        Map<String,String> map = new HashMap();
        Optional<PortalUserInfo> portalUser = portalUserInfoService.findByLoginPhoneNumberAndUserStatusNot(portalUserVo.getPhoneNumber(),3);
        if(portalUser==null){
            throw new ResponseException(403,"用户不存在");
        }
        portalUser.get().setLoginPassword(portalUserVo.getPassword());
        portalUser.get().setAccessToken("");
        redisUtil.hdel("portalUser",portalUser.get().getUserId());
        portalUserInfoService.update(portalUser.get());
        return JsonResult.success("设置成功");
    }

    @ApiOperation(value="个人用户中心接口", notes="根据userId查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户唯一标识（登录的用户必传）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accessToken", value = "访问令牌（登录的用户必传）", required = true, dataType = "String")
    })
    @PostMapping("/portalUser/getMyUserInfo")
    @CheckLogIn
    public JsonResult getMyUserInfo(@Valid BaseBody baseBody) {
        PortalUserInfoDto dto = portalUserInfoService.findMyPortalUserInfoDtoByUserId(baseBody.getUserId());
        return JsonResult.success("请求成功",dto);
    }


//    @ApiOperation(value="他人用户中心-用户信息接口", notes="根据userId查询用户信息")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "hisUserId", value = "用户唯一标识", required = true, dataType = "String"),
//    })
//    @PostMapping("/portalUser/getPortalUserInfo")
//    public JsonResult getPortalUserInfo(@Valid BaseBody baseBody,@NotEmpty(message = "用户Id不可为空") String hisUserId) {
//        PortalUserInfoDto portalUserInfoDto = portalUserInfoService.findPortalUserInfoDtoByUserId(hisUserId);
//        if(EmptyUtil.isEmpty(baseBody.getUserId())){
//            return JsonResult.success("请求成功",portalUserInfoDto);
//        }else{
//            FollowInfo followInfo = followInfoService.findByUserIdAndFollowUserId(baseBody.getUserId(), hisUserId);
//            if(EmptyUtil.isEmpty(followInfo)){
////                portalUserInfoDto.setIsFollow(1);
//            }else{
////                portalUserInfoDto.setIsFollow(2);
//            }
//            return JsonResult.success("请求成功",portalUserInfoDto);
//        }
//    }


}
